package scraper

import (
	"fmt"
	"strconv"

	"github.com/gocolly/colly"
)

type Realtime struct {
	Company    string
	Home, Away float64
	Handicap   string
}

type Match struct {
	Home, Away, Name, Time string
}

func Scrape(url string) (Match, []Realtime) {
	realtimes := []Realtime{}
  match := Match{}

	c := colly.NewCollector(
		colly.AllowedDomains("vip.titan007.com"),
	)

	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting:", r.URL)
	})

	c.OnError(func(_ *colly.Response, err error) {
		fmt.Println("Something went wrong:", err)
	})

	c.OnResponse(func(r *colly.Response) {
		fmt.Println("Page visited: ", r.Request.URL)
	})

	c.OnXML("//div[@class='analyhead']", func(e *colly.XMLElement) {
    match = Match{
    	Home: e.ChildText("/div[@class='home']"),
    	Away: e.ChildText("/div[@class='guest']"),
    	Name: e.ChildText("/div[@class='vs']/div[@class='row']/a[@class='LName']"),
    	Time: e.ChildText("/div[@class='vs']/div[@class='row']/span[@class='time']"),
    }
	})

	c.OnXML("//table[@id='odds']/tbody/tr", func(e *colly.XMLElement) {
		if e.Attr("bgcolor") == "#FFFFFF" || e.Attr("bgcolor") == "#FAFAFA" {
			company := e.ChildText("/td[1]")
			if company == "" {
				return
			}
			home, _ := strconv.ParseFloat(e.ChildText("/td[6]"), 64)
			handicap := e.ChildText("/td[7]")
			away, _ := strconv.ParseFloat(e.ChildText("/td[8]"), 64)

			realtimes = append(realtimes, Realtime{
				Company:  company,
				Home:     home,
				Handicap: handicap,
				Away:     away,
			})
		}
	})

	c.OnScraped(func(r *colly.Response) {
		fmt.Println(r.Request.URL, "scraped!")
	})

	c.Visit(url)

  return match, realtimes
}
